document.addEventListener("DOMContentLoaded", function() {
    getUserID().then(userId => {
        if (userId !== "not_logged_in") {
            fetchOrders(userId);
        } else {
            alert('用户未登录');
            window.location.href = '/index.html'; // 重定向到登录页面
        }
    });

    function fetchOrders(userId) {
        fetch(`/api/users/get-orders?userId=${userId}`, { // 获取特定用户的所有订单
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                const ordersInfoDiv = document.getElementById("orders-info");
                if (Array.isArray(data) && data.length > 0) {
                    ordersInfoDiv.innerHTML = `
                <table>
                    <tr>
                        <th>订单ID</th>
                        <th>总金额</th>
                        <th>状态</th>
                        <th>订单创建日期</th>
                        <th>操作</th>
                    </tr>
                    ${data.map(order => {
                        return `
                        <tr>
                            <td>${order.orderID}</td>
                            <td>${order.totalAmount}</td>
                            <td>${order.status}</td>
                            <td>${order.createTime}</td>
                            <td>
                                <button onclick="viewDetails(${order.orderID})">查看详情</button>
                                ${order.status === '未支付' ? `<button onclick="pay(${order.orderID}, '${order.subject}', ${order.totalAmount})">支付</button>` : ''}
                                <button onclick="deleteOrder(${order.orderID})">删除</button>
                            </td>
                        </tr>
                        `;
                    }).join('')}
                </table>
                `;
                } else {
                    ordersInfoDiv.textContent = "没有订单信息。";
                }
            })
            .catch(error => {
                console.error('Error:', error);
                ordersInfoDiv.textContent = "获取订单信息失败：" + error.message;
            });
    }

    window.viewDetails = function (orderId) {
        const orderDetailsDiv = document.getElementById("orders-info");
        fetch(`/api/orders/${orderId}`, { // 获取特定订单的详细信息
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(order => {
                if (order) {
                    orderDetailsDiv.innerHTML = `
                <div>
                    <p>订单ID: ${order.orderID}</p>
                    <p>总金额: ${order.totalAmount}</p>
                    <p>状态: ${order.status}</p>
                    <p>订单创建日期: ${order.createTime}</p>
                    ${order.details.map(detail => `
                        <div>
                            <a href="${detail.product.detailUrl}" target="_blank">
                                <img src="${detail.product.imageURL}" alt="${detail.product.name}" style="width:100px;height:100px;">
                                <p>${detail.product.name}</p>
                            </a>
                            <p>数量: ${detail.quantity}</p>
                            <p>单价: $${detail.unitPrice}</p>
                            <p>小计: $${detail.subtotal}</p>
                            <p>订单收货姓名:${order.shippingAddress.recipientName}</p>
                            <p>订单收获电话:${order.shippingAddress.phone}</p>
                            <p>订单收货地址:${order.shippingAddress.address}</p>
                        </div>
                    `).join('')}
                    <button onclick="window.location.reload()">返回订单列表</button>
                </div>
                `;
                } else {
                    orderDetailsDiv.textContent = "订单详情加载失败。";
                }
            })
            .catch(error => {
                console.error('Error:', error);
                orderDetailsDiv.textContent = "获取订单详情失败：" + error.message;
            });
    }

    window.pay = function(orderId, subject, totalAmount) {
        axios.get(`/api/alipay/pay?subject=${subject}&traceNo=${orderId}&totalAmount=${totalAmount}`)
            .then(response => {
                var payWindow = window.open('', '_blank');
                payWindow.document.write(response.data);
                payWindow.document.close();
            })
            .catch(error => {
                console.error('支付请求失败:', error);
                alert('支付请求失败');
            });
    };

    window.deleteOrder = function(orderId) {
        if (!confirm('确定要删除这个订单吗？')) return;

        fetch(`/api/orders/${orderId}`, {
            method: 'DELETE',
            credentials: 'include'
        })
            .then(response => {
                if (response.ok) {
                    fetchOrders(getUserID()); // 重新加载订单列表
                } else {
                    alert("删除失败");
                }
            })
            .catch(error => {
                console.error('Error deleting order:', error);
            });
    };

    function getUserID() {
        return fetch('/api/get-user-id', {
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to fetch user ID');
                }
                return response.text();
            })
            .catch(error => {
                console.error('Error fetching user ID:', error);
                alert('无法获取用户ID');
                return Promise.resolve("not_logged_in");
            });
    }
});